<template>
  <div id="lab-schedule">
    <Table :border="showBorder" :stripe="showStripe" :show-header="showHeader" :height="fixedHeader ? tableHeight : ''"
           :size="tableSize" :data="tableData" :columns="tableColumns" :loading="tableLoading" :disabledHover="disabledHover">
      <template slot-scope="{ row, index }" slot="section">
        <span>第 {{ index + 1 }} 节</span>
      </template>
      <template v-for="(value, i) in weekdays" slot-scope="{ row, index }" :slot="i + 1">
        <div v-for="(cnt, index) in row[i + 1].content" :key="index">
          <div class="detail-link" @click="getDetail(cnt)">
            <div>
              <span>课程：{{ cnt.courseName }}</span>
              <span class="d-none">**</span>
            </div>
            <div>
              <span>老师：{{ cnt.teacherName }}</span>
              <span class="d-none">**</span>
            </div>
            <div>
              <div v-for="item in cnt.classes.map(c => { return c.grade + c.major + c.sclass + '班' })" :key="item">
                <span>班级：{{ item }}</span>
                <span class="d-none">**</span>
              </div>
            </div>
            <div v-if="!filter.week || filter.week === 'all'">
              <span>周次：{{ cnt.weekNumber.join('、') }}<span class="d-none">**</span></span>
            </div>
          </div>
          <Divider v-if="index < row[i + 1].content.length - 1" style="height: 1.5px; margin: 15px 0;" />
          <span v-if="index < row[i + 1].content.length - 1" class="d-none">**</span>
        </div>
      </template>
    </Table>
    <div class="modal-container">
      <Modal v-model="modal.detail.show" footer-hide width="90%" class="mb-50-modal">
        <p slot="header" class="text-center" style="color: #276f86;">{{ modal.detail.title }}</p>
        <applied-form-detail-table v-if="modal.detail.show" :code="modal.detail.code"/>
      </Modal>
    </div>
  </div>
</template>

<script>
import { getLabSchedule } from '@/api/lab-schedule'
import AppliedFormDetailTable from '_c/applied-form-detail-table/applied-form-detail-table'
import { activeTableMove } from '@/libs/tools'
export default {
  name: 'LabSchedule',
  components: {
    'applied-form-detail-table': AppliedFormDetailTable
  },
  props: {
    filter: {
      type: Object,
      default: function () {
        return {
          institute: '',
          week: 'all',
          labCode: ''
        }
      }
    }
  },
  data () {
    return {
      firstEnter: false,
      weekdays: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      showBorder: true,
      showStripe: false,
      showHeader: true,
      tableData: [],
      tableColumns: [],
      fixedHeader: true,
      tableHeight: '',
      disabledHover: true,
      tableLoading: false,
      tableSize: 'default',
      modal: {
        detail: {
          show: false,
          title: '',
          code: ''
        }
      }
    }
  },
  methods: {
    // 初始化表格表头
    initTableHeader: function () {
      this.tableColumns.push({
        title: '节次',
        slot: 'section',
        key: 'section',
        align: 'center',
        width: 100
        // ,fixed: 'left'
      })
      this.weekdays.forEach((item, index) => {
        this.tableColumns.push({
          title: item,
          slot: index + 1,
          key: index + 1,
          align: 'center',
          minWidth: 240,
          className: 'row-combined'
        })
      })
    },
    // 处理表格数据
    handleTableData (tableData) {
      tableData.map(value => {
        value.cellClassName = {}
        this.weekdays.forEach((item, index) => {
          if (value[index + 1].content) {
            value.cellClassName[index + 1] = 'custom-table-cell-style'
          }
        })
        return value
      })
      // 行合并（上下合并）
      let i
      let j
      let len = tableData.length
      for (let w = 1; w <= this.weekdays.length; w++) {
        for (i = 0; i < len; i = j) {
          let item1 = tableData[i][w]
          item1.rowSpan = 1
          item1.show = true
          if (Object.prototype.toString.call(item1.content) === '[object Array]') {
            tableData[i].cellClassName[w] = 'custom-table-cell-style'
            for (j = i + 1; j < len; j++) {
              let item2 = tableData[j][w]
              item2.rowSpan = 1
              item2.show = true
              if (Object.prototype.toString.call(item2.content) === '[object Array]') {
                if (JSON.stringify(item1.content) === JSON.stringify(item2.content)) {
                  item1.rowSpan++
                  item2.show = false
                } else {
                  break
                }
              } else {
                break
              }
            }
          } else {
            j = i + 1
          }
        }
      }
      return tableData
    },
    // 获取数据渲染表格
    async renderTable (filter) {
      // 初始化表格
      this.tableLoading = true
      this.tableData = []
      this.tableColumns = []
      // 加载表头
      this.initTableHeader()
      // 获取表格数据
      try {
        let response = await getLabSchedule(filter)
        let res = response.data
        if (res.code === 1) {
          this.tableData = res.data.length > 0 ? this.handleTableData(res.data) : []
          this.$nextTick(() => {
            document.querySelectorAll('#lab-schedule .ivu-table-body td.row-combined').forEach((item, index) => {
              let row = this.tableData[Math.floor(index / this.weekdays.length)]
              let cell = index % this.weekdays.length + 1
              if (row[cell]) {
                item.setAttribute('rowspan', row[cell].rowSpan || 1)
                item.style.display = row[cell].show ? '' : 'none'
                if (!row[cell].show) {
                  item.parentNode.removeChild(item)
                }
              }
            })
            this.tableLoading = false
          })
        } else {
          this.tableColumns = []
          this.tableLoading = false
          this.$Notice.error({
            title: '列表加载失败',
            desc: '实验室安排表加载失败！' + res.info
          })
        }
      } catch (error) {
        this.tableColumns = []
        this.tableLoading = false
        this.$Notice.error({
          title: '列表加载失败',
          desc: '实验室安排表加载失败！'
        })
        console.log(error)
      }
    },
    // 查看详情
    getDetail (content) {
      this.modal.detail.title = content.teacherName + '老师的' + '《' + content.courseName + '》课程相关的实验课信息登记表'
      this.modal.detail.show = true
      this.modal.detail.code = content.code || ''
    }
  },
  created () {
    this.firstEnter = true
    this.$Notice.config({
      top: window.innerHeight / 3
    })
  },
  mounted () {
    this.$nextTick(() => {
      activeTableMove(document.querySelector('#lab-schedule .ivu-table-body'))
      if (!this.filter.labCode) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择实验室进行检索！'
        })
      }
    })
  },
  activated () {
    if (!this.firstEnter) {
      this.$Notice.config({
        top: window.innerHeight / 3
      })
      if (!this.filter.labCode) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择实验室进行检索！'
        })
      }
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    filter: {
      handler: function (value) {
      //   let state = true
      //   for (let key in value) {
      //     if (value.hasOwnProperty(key)) {
      //       if (!value[key]) {
      //         state = false
      //         break
      //       }
      //     } else {
      //       state = false
      //       break
      //     }
      //   }
      //   if (state) {
      //     this.renderTable(value)
      //   }
        if (!value.labCode) {
          this.tableData = []
          this.tableColumns = []
        } else {
          this.renderTable(value)
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
  #lab-schedule {
    /*.ivu-table-wrapper {*/
      /*border-top: .2em solid #21ba45;*/
      /*border-radius: .3rem;*/
    /*}*/
  }
</style>
<style lang="less">
  #lab-schedule {
    .custom-table-cell-style {
      background-color: #ebf7ff !important;
      color: #276f86;
    }
    .ivu-table {
      &-tbody {
        .ivu-table-cell {
          padding-top: 10px;
          padding-bottom: 10px;
          font-size: 0.825rem;
          font-weight: bold;
        }
      }
      &-wrapper {
        border-color: #ccc;
      }
      &-border {
        & th {
          border-color: #ccc;
        }
        & td {
          border-color: #ccc;
        }
      }
      .detail-link {
        line-height: 1.5rem;

        &:hover {
          cursor: pointer;
          color: #2D8cF0;
          text-decoration: underline;
        }
      }
    }
  }
</style>
